<template>
  <div class="dish-detail">
    <button @click="goBack" class="back-button">← 返回列表</button>

    <!-- 图片展示区域 -->
    <div class="dish-image-container">
      <div v-if="isEditing" class="edit-image-container">
        <label class="image-label">菜品图片</label>
        <div class="image-preview-container">
          <div class="image-preview" @click="$refs.fileInput.click()">
            <img 
              v-if="previewImageUrl" 
              :src="previewImageUrl" 
              alt="菜品预览图" 
              class="preview-image"
            >
            <div v-else class="no-image-placeholder">
              <i class="fa fa-camera fa-3x mb-2"></i>
              <span>点击上传图片</span>
            </div>
          </div>
        </div>
        <input 
          type="file" 
          ref="fileInput" 
          @change="handleFileUpload" 
          accept="image/*" 
          class="file-input"
        >
      </div>

      <div v-else class="view-image-container">
        <div class="image-display">
          <img 
            v-if="dish.url" 
            :src="dish.url" 
            alt="菜品图片" 
            class="dish-image"
          >
          <div v-else class="no-image-placeholder">
            <i class="fa fa-image fa-4x mb-3"></i>
            <span>暂无菜品图片</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑模式表单 -->
    <div v-if="isEditing" class="edit-form">
      <h2>编辑菜品</h2>
      <input v-model="currentDish.dishName" placeholder="菜品名称">
      <input v-model.number="currentDish.price" type="number" placeholder="价格">
      <input v-model.number="currentDish.merchantId" type="number" placeholder="商家ID">
      <textarea v-model="currentDish.description" placeholder="描述"></textarea>
      
      <div class="action-buttons">
        <button @click="saveDish" class="save-button">保存</button>
        <button @click="cancelEdit" class="cancel-button">取消</button>
        <button 
          @click="deleteDish" 
          class="delete-button"
        >
          删除菜品
        </button>
      </div>
    </div>

    <!-- 只读模式展示 -->
    <div v-else class="read-mode">
      <h1>{{ dish.dishName }}</h1>
      <div class="dish-info">
        <p><strong>菜品ID:</strong> {{ dish.dishId }}</p>
        <p><strong>价格:</strong> ¥{{ dish.price }}</p>
        <p><strong>商家ID:</strong> {{ dish.merchantId }}</p>
        <p><strong>描述:</strong> {{ dish.description }}</p>
      </div>
      <button @click="startEdit" class="edit-button">编辑</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const fileInput = ref(null);
const previewImageUrl = ref('');
const selectedFile = ref(null);

const BASE_URL = 'http://localhost:8080/healtheat208';

// 响应式数据
const dish = ref({
  dishId: null,
  dishName: '',
  price: 0,
  merchantId: null,
  description: '',
  url: ''
});
const currentDish = ref({
  dishId: null,
  dishName: '',
  price: 0,
  merchantId: null,
  description: '',
  url: ''
});
const isEditing = ref(false);

// 返回列表页
const goBack = () => {
  router.push({ name: 'dishesList' });
};

// 获取菜品详情
const fetchDish = async () => {
  try {
    const dishId = route.params.id;
    if (!dishId) {
      router.push({ name: 'dishesList' });
      return;
    }
    
    const response = await axios.get(`${BASE_URL}/Dish/list/${dishId}`);
    if (response.data) {
      dish.value = { ...response.data };
      currentDish.value = { ...response.data };
      previewImageUrl.value = response.data.url || '';
    } else {
      throw new Error('未找到菜品数据');
    }
  } catch (error) {
    console.error('获取菜品详情失败:', error);
    alert('获取菜品详情失败，请稍后重试');
    router.push({ name: 'dishesList' });
  }
};

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (!file) return;
  
  selectedFile.value = file;
  
  // 创建预览URL
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImageUrl.value = e.target.result;
  };
  reader.readAsDataURL(file);
};

// 保存菜品
const saveDish = async () => {
  try {
    // 更新菜品
    if (selectedFile.value) {
      const imageUrl = await uploadImage(selectedFile.value);
      currentDish.value.url = imageUrl;
    }
    
    await axios.put(`${BASE_URL}/Dish/update`, currentDish.value);
    alert('菜品更新成功');
    fetchDish();
    isEditing.value = false;
  } catch (error) {
    console.error('保存菜品失败:', error);
    alert(`保存失败: ${error.response?.data?.message || error.message}`);
  }
};

// 上传图片到服务器
const uploadImage = async (file) => {
  try {
    const formData = new FormData();
    formData.append('image', file);
    
    const response = await axios.post(`${BASE_URL}/upload/image`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    
    return response.data.url;
  } catch (error) {
    console.error('上传图片失败:', error);
    throw new Error('图片上传失败，请重试');
  }
};

// 删除菜品
const deleteDish = async () => {
  if (!confirm('确定要删除这个菜品吗？')) return;
  
  try {
    const dishId = route.params.id;
    if (!dishId) throw new Error('菜品ID不存在');
    
    await axios.delete(`${BASE_URL}/Dish/delete/${dishId}`);
    alert('菜品删除成功');
    router.push({ name: 'dishesList' });
  } catch (error) {
    console.error('删除菜品失败:', error);
    alert(`删除失败: ${error.response?.data?.message || error.message}`);
  }
};

// 进入编辑模式
const startEdit = () => {
  isEditing.value = true;
  previewImageUrl.value = dish.value.url || '';
};

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false;
  previewImageUrl.value = dish.value.url || '';
  selectedFile.value = null;
  currentDish.value = { ...dish.value };
};

// 组件挂载后加载数据
onMounted(() => {
  fetchDish();
});
</script>

<style scoped>
.dish-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.back-button {
  background: #6c757d;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 20px;
  display: inline-block;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: #5a6268;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.dish-image-container {
  margin: 20px 0;
  max-width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-label {
  font-weight: 600;
  margin-bottom: 10px;
  display: block;
  color: #333;
}

.image-preview-container {
  width: 100%;
  max-width: 500px;
  position: relative;
}

.image-preview, .image-display {
  width: 100%;
  aspect-ratio: 16/9;
  background-color: #f8f9fa;
  border: 2px solid #ddd;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.image-preview:hover, .image-display:hover {
  border-color: #007bff;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.preview-image, .dish-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  transition: transform 0.5s ease;
}

.preview-image:hover, .dish-image:hover {
  transform: scale(1.02);
}

.no-image-placeholder {
  color: #6c757d;
  font-size: 14px;
  text-align: center;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.no-image-placeholder i {
  margin-bottom: 10px;
  color: #ccc;
}

.file-input {
  display: none;
}

.edit-form, .read-mode {
  background: #f8f9fa;
  padding: 25px;
  border-radius: 8px;
  margin-top: 20px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}

.edit-form input,
.edit-form textarea {
  width: 100%;
  padding: 10px 12px;
  margin-bottom: 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
  transition: all 0.3s ease;
}

.edit-form input:focus,
.edit-form textarea:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.edit-form textarea {
  height: 120px;
  resize: vertical;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.save-button {
  background: #28a745;
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  flex-grow: 1;
  transition: all 0.3s ease;
  font-weight: 500;
}

.save-button:hover {
  background: #218838;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.cancel-button {
  background: #6c757d;
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  flex-grow: 1;
  transition: all 0.3s ease;
  font-weight: 500;
}

.cancel-button:hover {
  background: #5a6268;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.delete-button {
  background: #dc3545;
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  flex-grow: 1;
  transition: all 0.3s ease;
  font-weight: 500;
}

.delete-button:hover {
  background: #c82333;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.read-mode h1 {
  margin-bottom: 15px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.dish-info p {
  margin: 12px 0;
  line-height: 1.6;
  color: #555;
}

.dish-info strong {
  color: #333;
}

.edit-button {
  background: #007bff;
  color: white;
  border: none;
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 15px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.edit-button:hover {
  background: #0069d9;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

@media (max-width: 600px) {
  .action-buttons {
    flex-direction: column;
  }
  
  .edit-button {
    width: 100%;
    margin-left: 0;
    margin-right: 0;
  }
}
</style>